/*
* Copyright 2016 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project Name : marketing-service-newcar-showroom
*
* @File name : CommonUtils.java
*
* @Author : LiuJun
*
* @Date : 2016年11月1日
*
----------------------------------------------------------------------------------
*     Date       Who       Version     Comments
* 1. 2016年11月1日    LiuJun    1.0
*
*
*
*
----------------------------------------------------------------------------------
*/
	
package org.marketing.common.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.marketing.common.exception.ServiceBizException;

/**
*
* @author LiuJun
* 公共工具类
* @date 2016年11月1日
*/
public class CommonUtils {
    
    public final static String EMPTY_STRING = "";

    
    /**
     * check if null or empty string
     */
    public static boolean isNullOrEmpty(String str) {
        return (null == str || EMPTY_STRING.equals(str));
    }

    /**
     * check if the list is null or empty
     */
    public static boolean isNullOrEmpty(Collection<?> list) {
        return list == null || list.isEmpty();
    }

    /**
     * check if the map is null or empty
     */
    public static boolean isNullOrEmpty(Map<?, ?> map) {
        return map == null || map.isEmpty();
    }
    
    /**
     * check if the integer is null or 0
     */
    public static boolean isNullOrO(Integer integer) {
        return integer == null || integer.equals(0);
    }

    /**
     * check if the long is null or 0
     */
    public static boolean isNullOrOLong(Long l) {
        return l == null || l.equals(0L);
    }
    
    /**
     * check if the bigDecimal is null or 0
     */
    public static boolean isNullOrOBigDecimal(BigDecimal bigd) {
        if(bigd == null){
            return true;
        }
        int num= bigd.compareTo(BigDecimal.ZERO);
        return num==0;
    }
    
    /**
     * 输出获得对象中所有成员变量的值
     * 
     * @author WangHuicheng
     * @date 2016年12月23日
     * @param obj
     * @return
     */
    public static String toString(Object obj) {
        StringBuffer result = new StringBuffer();
        result.append(obj.getClass().getName() + "的成员变量值如下：");
        try {
            Field[] fields = obj.getClass().getDeclaredFields();

            for (int i = 0; i < fields.length; i++) {
                fields[i].setAccessible(true);
                result.append(fields[i].getName() + ":" + fields[i].get(obj) + "\r\n");
            }
        } catch (Exception e) {
            result.append(obj.getClass().getName() + "的成员变量值读取失败：" + e.getMessage());
        }
        return result.toString();
    }
    
    // 签名生成代码
 	public static Map<String, Object> generateSign(Map<String, Object> parm, String secretKey) throws NoSuchAlgorithmException {
 		String _sign = "";
 		if (null != parm) {
 			Collection<String> keyset = parm.keySet();
 			List<String> list = new ArrayList<>(keyset);
 			Collections.sort(list);
 			for (int i = 0; i < list.size(); i++) {
 				_sign += list.get(i) + "=" + parm.get(list.get(i));
 			}
 			_sign = bytesToMD5((bytesToMD5(_sign.getBytes()) + secretKey).getBytes());
 		}
 		parm.put("sign", _sign);
 		return parm;
 	}
 	// 返回签名生
  	public static String genSign(Map<String, Object> parm, String secretKey) throws NoSuchAlgorithmException {
  		String _sign = "";
  		if (null != parm) {
  			Collection<String> keyset = parm.keySet();
  			List<String> list = new ArrayList<>(keyset);
  			Collections.sort(list);
  			for (int i = 0; i < list.size(); i++) {
  				_sign += list.get(i) + "=" + parm.get(list.get(i));
  			}
  			_sign = bytesToMD5((bytesToMD5(_sign.getBytes()) + secretKey).getBytes());
  		}
  		return _sign;
  	}
 	// 把字节数组转换成md5
     public static String bytesToMD5(byte[] input) throws NoSuchAlgorithmException {
    	// 创建一个提供信息摘要算法的对象，初始化为md5算法对象
         MessageDigest md = MessageDigest.getInstance("MD5");
         // 计算后获得字节数组
         byte[] buff = md.digest(input);
         // 把数组每一字节换成16进制连成md5字符串
         return bytesToHex(buff);
     }
     
     public static String bytesToHex(byte[] bytes) {
         StringBuffer md5str = new StringBuffer();
         //把数组每一字节换成16进制连成md5字符串
         int digital;
         for (int i = 0; i < bytes.length; i++) {
              digital = bytes[i];
             if(digital < 0) {
                 digital += 256;
             }
             if(digital < 16){
                 md5str.append("0");
             }
             md5str.append(Integer.toHexString(digital));
         }
         return md5str.toString();
     }
     /**
      * 取出一个指定长度大小的随机正整数.
      * 
      * @param length int 设定所取出随机数的长度。length小于11
      * @return int 返回生成的随机数。
      */
     public static int buildRandom(int length) {
         int num = 1;
         double random = Math.random();
         if (random < 0.1) {
             random = random + 0.1;
         }
         for (int i = 0; i < length; i++) {
             num = num * 10;
         }
         return (int) ((random * num));
     }
     /**
      * 生成随机数，包括数字
      * 
      * @param length int 设定所取出随机数的长度。length小于8
      * @return int 返回生成的随机数。
      */
     @SuppressWarnings("rawtypes")
     public static String randomCode(int length){
         
 	    String result = "";
         String[] beforeShuffle = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
         List list = Arrays.asList(beforeShuffle);
         Collections.shuffle(list);
         StringBuilder sb = new StringBuilder();
         for (int i = 0; i < list.size(); i++) {
             sb.append(list.get(i));
         }
         String afterShuffle = sb.toString();
         result = afterShuffle.substring(2, 2+length);
         return result;
     }
     /**
      * 生成随机数，包括数字和大写字母
      * 
      * @param length int 设定所取出随机数的长度。length小于34
      * @return int 返回生成的随机数。
      */
     @SuppressWarnings("rawtypes")
     public static String randomCodeZ(int length){
         
 	    String result = "";
 	    String[] beforeShuffle = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C",
               "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
               "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
         List list = Arrays.asList(beforeShuffle);
         Collections.shuffle(list);
         StringBuilder sb = new StringBuilder();
         for (int i = 0; i < list.size(); i++) {
             sb.append(list.get(i));
         }
         String afterShuffle = sb.toString();
         result = afterShuffle.substring(2, 2+length);
         return result;
     }
     /**
      * 生成随机OPENID，包括数字、大小写字母、下划线和横线
      * 
      * @param length int 设定所取出随机数的长度。length为30 ，以APP...开头
      * @return int 返回生成的随机OPENID。
      */
     @SuppressWarnings("rawtypes")
     public static String randomOpenId(){
         
 	    String result = "";
         String[] beforeShuffle = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C",
                                                 "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
                                                 "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c",
                                                 "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p",
                                                 "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "-", "_" };
         List list = Arrays.asList(beforeShuffle);
         Collections.shuffle(list);
         StringBuilder sb = new StringBuilder("APP");
         for (int i = 0; i < list.size(); i++) {
             sb.append(list.get(i));
         }
         String afterShuffle = sb.toString();
         result = afterShuffle.substring(0, 30);
         return result;
     }

     /**
      * 根据路径获取内容
      * 
      * @author QianKun
      * @date 2017年3月10日
      * @param naiId
      * @return
      */
     public static String getUrlToContent(String url)  {

      // url = url.replaceAll("(?<=\\//)(.*?)(?=\\/f)", inforHost);
         if (CheckUtil.NullOrEmpty(url)) {
             return EMPTY_STRING;
         }
         InputStream inputStream = null;
         ByteArrayOutputStream output = null;
         try {
             URL urlTemp = new URL(url);
             HttpURLConnection httpConn = (HttpURLConnection) urlTemp.openConnection();

             httpConn.connect();
             inputStream = httpConn.getInputStream();
             // filestore

             output = new ByteArrayOutputStream();
             byte[] buffer = new byte[4096];
             int n = 0;
             while (-1 != (n = inputStream.read(buffer))) {
                 output.write(buffer, 0, n);
             }
             String resultContent = output.toString("utf-8");
             return resultContent;
         } catch (Exception e) {
             throw new ServiceBizException(e.getMessage(), e);
         } finally {
             try {
                 if (inputStream != null) inputStream.close();
             } catch (Exception e) {
             }
             try {
                 if (output != null) output.close();
             } catch (Exception e) {
             }

         }
     }
}
